package com.sunsharing.flow.model.node;

import com.sunsharing.common.anno.Factory;
import com.sunsharing.common.utils.MyByteReadParanamer;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.flow.exe.ExecutionContext;
import com.sunsharing.flow.exe.WorkFlowService;
import org.apache.log4j.Logger;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-5-8
 * Time: 下午10:37
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="java")
public class JavaCall extends Call {

    transient Logger logger = Logger.getLogger(JavaCall.class);
    String cls;
    String method;

    transient Method me;
    transient Object obj;
    //入参名
    String[] pars;
    public String getCls() {
        return cls;
    }

    public void setCls(String cls) {
        this.cls = cls;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }



    public void initMethod()throws Exception
    {
        Class demo= Class.forName(cls);
        obj = demo.newInstance();
        Method[] m = demo.getDeclaredMethods();
        for(Method t:m)
        {
            if(t.getName().equals(method))
            {
                me = t;
                MyByteReadParanamer paranamer = new MyByteReadParanamer();
                //paranamer.byteCode = byteCode;
                pars = paranamer.lookupParameterNames(me);
                if(pars!=null && pars.length==1 && StringUtils.isBlank(pars[0]))
                {
                    pars = null;
                }
                break;
            }
        }
    }

    public boolean call(ExecutionContext context)
    {
        //Map par = context.getToken().getPar();
        Object[] objs = null;
        try
        {
            ExecutionContext.setExcutionContext(context);
            if(pars==null)
            {
                pars = new String[0];
            }
            if(pars!=null)
            {
                objs = new Object[pars.length];
                //Map ts = .getPar();
                for(int i=0;i<pars.length;i++)
                {
                    objs[i] = context.getToken().getPar(pars[i]);
                }
                Object o = null;
                if(objs==null || objs.length==0)
                {
                    o = me.invoke(obj);
                }else
                {
                    o = me.invoke(obj,objs);
                }
                if(output!=null)
                {
                    context.getToken().putPar(output,o);
                }
            }

        }catch (Exception e)
        {
            logger.error("调用出错",e);
            throw new RuntimeException("调用出错");
        }finally {
            ExecutionContext.removeExcutionContext();
        }
        return false;
    }
}
